package cn.jett.domain.strategy.service.rule.chain.factory;

import cn.jett.domain.strategy.model.entity.StrategyEntity;
import cn.jett.domain.strategy.repository.IStrategyRepository;
import cn.jett.domain.strategy.service.rule.chain.ILogicChain;
import cn.jett.types.common.Constants;
import lombok.*;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @Author 战斗天使
 * @Description 责任链工厂
 * @Date 2024/6/19
 */
@Service
public class DefaultChainFactory {

    private final Map<String, ILogicChain> logicChainGroup;

    protected final IStrategyRepository repository;

    //将所有过滤链节点装配（在过滤节点类上用component("...")标注过滤规则名）
    public DefaultChainFactory(Map<String, ILogicChain> logicChainGroup, IStrategyRepository repository) {
        this.logicChainGroup = logicChainGroup;
        this.repository = repository;
    }

    /**
     * 过滤链工厂 - 构造出该策略所配置的所有规则过滤链
     * @param strategyId
     * @return
     */
    public ILogicChain openLogicChain(Long strategyId){
        //查询策略所配置的规则
        StrategyEntity strategy = repository.queryStrategyEntityByStrategyId(strategyId);
        String ruleModels = strategy.getRuleModels();
        String[] splitRuleModels = ruleModels.split(Constants.SPLIT);
        //没配置规则 过滤链只装默认过滤节点
        if(null == ruleModels || 0==ruleModels.length()){
            return logicChainGroup.get(LogicModel.RULE_DEFAULT.code);
        }
        //构造过滤链
        ILogicChain logicChain = logicChainGroup.get(splitRuleModels[0]);
        ILogicChain current = logicChain;
        for (int i = 1; i < splitRuleModels.length; i++) {
            ILogicChain nextChain = logicChainGroup.get(splitRuleModels[i]);
            current = current.appendNext(nextChain);
        }
        current.appendNext(logicChainGroup.get(LogicModel.RULE_DEFAULT.code));

        return logicChain;
    }

    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public static class StrategyAwardVO {
        /** 抽奖奖品ID - 内部流转使用 */
        private Integer awardId;
        /**  */
        private String logicModel;
    }

    @Getter
    @AllArgsConstructor
    public enum LogicModel {

        RULE_DEFAULT("rule_default", "默认抽奖"),
        RULE_BLACKLIST("rule_blacklist", "黑名单抽奖"),
        RULE_WEIGHT("rule_weight", "权重规则"),
        ;

        private final String code;
        private final String info;

    }
}
